import config from '../config.js'

/**
 * url 不需要host
 * @param {
 *  url, 
 *  method,
 *  data
 * } params 
 * 
 * 
 */
export default function authRequest(params) {
  let openId = wx.getStorageSync('openid');
  let header = {
    'userKey': openId
  }

  if (params.header) {
    header = Object.assign(header, params.header);
  }

  return new Promise((resolve, rejected) => {
    wx.request({
      url: 'url',
    })
    wx.request({
      header:header,
      url: config.host + params.url,
      method: params.method ? params.method : 'GET',
      data: params.data ? params.data : {},
      success: function (res) {
        //没有登录成功会一直登录 这个登录的判断根据后台的接口具体改写
        if (res.statusCode == 511) {
          login().then(()=>{
            return authRequest(params)
          })
        }else{
          resolve(res)
        }
        
      },
      fail: function (e) {
        rejected(e)
      }
    })
  });

}

function login(){
  return new Promise((resolve,rejected)=>{
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url:config.host + "/xcx/user/login",
          method:'GET',
          data:{
            code:res.code
          },
          success:function(res){
            wx.setStorageSync("openid",res.data)
            resolve()
          }
        })
      }
    })
  })
    
}